package gvo.dbinfo;
import gvo.sql.SQLWizard;

import java.sql.Date;
import java.sql.Types;


public class SarFieldInfo implements Comparable<SarFieldInfo> {
	public String fieldName;
	public String columnTypeName;
	public int columnTyp;


	public SarFieldInfo(String fieldName, String columnTypeName, int columnTyp) {
		this.fieldName = fieldName;
		this.columnTypeName = columnTypeName;
		this.columnTyp = columnTyp;
	}
	public int compareTo(SarFieldInfo o1)  {
		
        return fieldName.compareTo(o1.fieldName);
		
    }
	public String printInfo() {
		return String.format("%1$-22s%2$-22s%3$-4d", fieldName, columnTypeName,
				columnTyp);
	}

	public String toString() {
		return fieldName;
	}
	
	public String createSetString(String in){
		String res = " SET " +fieldName;
		if (columnTyp == Types.VARCHAR) {
			res =  res + "='" + SQLWizard.prepSQLString(in) + "'";
		} else if (columnTyp == Types.INTEGER) {
			if (in.equals("")) {
				res = res + " = NULL";
			} else {
				int a;
				try {
					a = Integer.parseInt(in);
					res = res + "=" + String.valueOf(a);
				} catch (NumberFormatException e) {
					System.out.println(in + " muss eine Zahl sein!");
				}
			}
		} else if (columnTyp == Types.DATE) {
			Date dt = null;
			try {
				dt = Date.valueOf(in);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
				return null;
			}
			res = res + "='" + dt.toString() + "'";
		} else {
			// Rest
			res = null;
		}
	
		return res;
	}
	public String createWhereString(String in, boolean ls, boolean rs) {
		String res = null;
		if (ls || rs) {
			if (in.equals("")){
				return null;
			}else if (ls && rs){
					res = fieldName + " like '%" + SQLWizard.prepSQLString(in) + "%'"; 
			}else if (ls && !rs){
					res = fieldName + " like '%" + SQLWizard.prepSQLString(in) + "'";
			}else{
					res = fieldName + " like '" + SQLWizard.prepSQLString(in) + "%'" ;
			} 
		} else {
			
			if (columnTyp == Types.VARCHAR) {
				res = fieldName + "='" + SQLWizard.prepSQLString(in) + "'";
			} else if (columnTyp == Types.INTEGER) {
				if (in.equals("")) {
					res = fieldName + " IS NULL";
				} else {
					int a;
					try {
						a = Integer.parseInt(in);
						res = fieldName + "=" + String.valueOf(a);
					} catch (NumberFormatException e) {
						System.out.println(in + " muss eine Zahl sein!");
					}
				}
			} else if (columnTyp == Types.DATE) {
				Date dt = null;
				try {
					dt = Date.valueOf(in);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
					return null;
				}
				res = fieldName + "='" + dt.toString() + "'";
			} else {
				// Rest
				res = null;
			}
			
			
		}
		return res;
	}
}